from setuptools import find_packages, setup
from setuptools.command.install import install as _install
from setuptools.command.develop import develop as _develop

import importlib
import logging
import os
import shutil
import subprocess

logger = logging.getLogger(__name__)

external_requirements = [
    'cython',
    'numpy',
    'scipy',
    'pandas',
    'matplotlib',
    'six',
    'pymetis'
]

internal_requirements = {
    "misc":  "-e git+https://bitbucket.org/bmmalone/misc.git#egg=misc" 
        # the "-e" seems to be necessary to grab subfolders. I do not
        # understand this, but it seems to work
}

def _post_install(self):
    import site
    importlib.reload(site)

    import misc.utils as utils

    programs = ['astar', 'score']
    utils.check_programs_exist(programs, raise_on_error=False, 
        package_name='urlearning-cpp', logger=logger)


def install_requirements(is_user):
    """ This function checks if the packages specified in internal_requirements
        are already installed. If not, it uses the given location to install them.

        This is mostly taken from: http://stackoverflow.com/questions/14050281/how-to-check-if-a-python-module-exists-without-importing-it
    """
    
    is_user_str = ""
    if is_user:
        is_user_str = "--user"

    option = "install {}".format(is_user_str)
    for package_name, location in internal_requirements.items():
        # check if this package is already installed
        package_spec = importlib.util.find_spec(package_name)
        found = package_spec is not None

        if not found:
            cmd = "pip3 {} {}".format(option, location)
            subprocess.call(cmd, shell=True)


class my_install(_install):
    def run(self):
        level = logging.getLevelName("INFO")
        logging.basicConfig(level=level,
            format='%(levelname)-8s : %(message)s')

        _install.run(self)
        install_requirements(self.user)
        _post_install(self)

class my_develop(_develop):  
    def run(self):
        level = logging.getLevelName("INFO")
        logging.basicConfig(level=level,
            format='%(levelname)-8s : %(message)s')

        _develop.run(self)
        install_requirements(self.user)
        _post_install(self)


def readme():
    with open('README.md') as f:
        return f.read()

setup(name='urlearning',
        version='0.1',
        description="This package contains scripts for Bayesian networks.",
        long_description=readme(),
        keywords="bayesian networks urlearning bnsl",
        url="",
        author="Brandon Malone",
        author_email="bmmalone@gmail.com",
        license='MIT',
        packages=['urlearning'],
        install_requires = external_requirements,
        cmdclass={'install': my_install,  # override install
                  'develop': my_develop   # develop is used for pip install -e .
        },
        include_package_data=True,
        test_suite='nose.collector',
        tests_require=['nose'],
        entry_points = {
            'console_scripts': ['astar-workflow=urlearning.astar_workflow:main',
                                'create-component-grouping-pd=urlearning.create_component_grouping_pd:main',
                                'astar-decomposition=urlearning.astar_decomposition:main',
                                'merge-networks=urlearning.merge_networks:main',
                                'net2dimacs=urlearning.utils.net2dimacs:main',
                                'pss-to-jkl=urlearning.utils.pss_to_jkl:main',
                                'sort-pss=urlearning.utils.sort_pss:main'
                               ]
        },
        zip_safe=False
        )
